package com.hean.datasave;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.hean.service.FileService;

public class DataSaveActivity extends Activity {
	private static final String TAG="DataSaveActivity";
	private EditText filenameText;
	private EditText contentText;
	private TextView result;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.out.println("DataSaveActivity onCreate");
        
        setContentView(R.layout.main);
        filenameText=(EditText) this.findViewById(R.id.filename);
        contentText=(EditText) this.findViewById(R.id.contentText);
         
        result=(TextView) this.findViewById(R.id.result);
        
        Button button=(Button) this.findViewById(R.id.button);
        Button readButton=(Button) this.findViewById(R.id.read);
        
        button.setOnClickListener(listener);
        readButton.setOnClickListener(listener);
    }
    private View.OnClickListener listener=new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			System.out.println("onClick");
			Button button=(Button)v;
			String filename=filenameText.getText().toString();
			//文件保存到sdcard
			File file=new File(Environment.getExternalStorageDirectory(), filename);//Environment.getExternalStorageDirectory();//相当于new File("/sdcard")
			switch (button.getId()) {
			case R.id.button:
				
				int resId=R.string.success;
				String content=contentText.getText().toString();
				if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){//sdcard 存在，并且可以读写
					try {
//						OutputStream outputStream=DataSaveActivity.
//						this.openFileOutput(name, Context.MODE_PRIVATE);
						
						FileOutputStream outputStream=new FileOutputStream(file);
						FileService.save(outputStream, content);
					} catch (Exception e) {
						Log.i(TAG, e.toString());
						resId=R.string.error;
					}
					Toast.makeText(DataSaveActivity.this, resId, Toast.LENGTH_LONG).show();
				}else{
					Toast.makeText(DataSaveActivity.this, "sdcard dose not existed! or is protected写保护", Toast.LENGTH_LONG).show();
				}
				
				break;

			case R.id.read:
				try {
					//DataSaveActivity.this.openFileInput(filename)
					//从sdcard读取
					InputStream inputStream=new FileInputStream(file);
					String filecontent=FileService.read(inputStream);
					result.setText(filecontent);
				} catch (Exception e) {
					Log.i(TAG, e.toString());
				}
				break;
			}
		}
	};
}